package com.soso.adp.bpc.hatcher.io.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastServer implements Runnable {

	private MulticastSocket socket;
	private InetAddress group;

	@Override
	public void run() {
		while (true) {
			try {
				this.write();
				Thread.sleep(5000);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void write() throws IOException {
		String s = "hello";
		byte data[] = s.getBytes();
		DatagramPacket packet = new DatagramPacket(data, data.length, group, Multicast.PORT);
		try {
			socket = new MulticastSocket(Multicast.PORT);
			socket.setTimeToLive(1);
			socket.joinGroup(group);
			socket.send(packet);
			socket.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void init() {
		try {
			group = InetAddress.getByName(Multicast.HOST);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		MulticastServer server = new MulticastServer();
		server.init();
		new Thread(server).start();
	}
}
